//
//  MarketViewController.swift
//  Exchange
//
//  Created by rui on 2018/4/18.
//  Copyright © 2018年 common. All rights reserved.
//

import UIKit
import SDCycleScrollView
import Starscream
class MarketViewController: BaseViewController,UIScrollViewDelegate,UIGestureRecognizerDelegate {
    
    var canScroll = true
    
    lazy var navigationBar: MarketNavigationBar = {
        let bar = MarketNavigationBar(frame: CGRect(x: 0, y: 0, width: kSCREEN_WIDTH, height: kNavi_HEIGHT))
        return bar
    }()
    
    lazy var contentScroll: GestureScrollView = {
//        let rect = CGRect(x: 0, y: 0, width: self.view.width, height: self.view.height - self.tabBarController!.tabBar.height)
        let scroll = GestureScrollView(frame: self.view.bounds)
        scroll.autoresizingMask = [.flexibleHeight,.flexibleWidth]
        scroll.themeBackground = ThemeManager.ThemeColorKeys.background
        scroll.showsVerticalScrollIndicator = false
        scroll.showsHorizontalScrollIndicator = false
        scroll.delegate = self
        return scroll
    }()
    
    lazy var viewModel: MarketViewModel = {
        let vm = MarketViewModel()
        vm.response = {[weak self](state,isSuccess,errorMsg)in
            if state == ResponseState.home_banner_info  {
                if isSuccess {
                    self?.reloadBanner()
                }
            }
        }
        return vm
    }()
    
    lazy var cycleView: SDCycleScrollView = {
        let cycle = SDCycleScrollView(frame: CGRect(x: 0, y: 0, width: kSCREEN_WIDTH, height: 200.0 / 375.0 * kSCREEN_WIDTH), delegate: self, placeholderImage: nil)
        cycle?.localizationImageNamesGroup = [#imageLiteral(resourceName: "banner_1"),#imageLiteral(resourceName: "banner_2"),#imageLiteral(resourceName: "banner_3")]
        cycle?.pageControlDotSize = CGSize(width: 15, height: 2)
        cycle?.pageDotImage = #imageLiteral(resourceName: "banner_dot_normal")
        cycle?.currentPageDotImage = #imageLiteral(resourceName: "banner_dot_selected")
        return cycle!
    }()
    
    var tabbar: TabbarView?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationController?.setNavigationBarHidden(true, animated: false)
        navigationBar.alpha = 0.0
        if #available(iOS 11, *) {
            self.contentScroll.contentInsetAdjustmentBehavior = .never
        }else {
            self.automaticallyAdjustsScrollViewInsets = false
        }
        NotificationCenter.default.addObserver(self, selector: #selector(changeScroll), name: NSNotification.Name.Exchange.HomePageScroll, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(initData), name: NSNotification.Name.Exchange.RefreshBanner, object: nil)
        initUI()
        initData()
    }
    func initUI() {
        self.view.addSubview(contentScroll)
        contentScroll.addSubview(cycleView)
        self.view.addSubview(navigationBar)
        
        self.pushScreenLock()
    }
    
    @objc func initData() {
        self.viewModel.loadBannerInfo()
    }
    
    @objc func changeScroll() {
        canScroll = true
        resetCanScroll(canScroll: false)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.tabbar?.getCurPageController()?.viewWillAppear()
        self.scrollViewDidScroll(self.contentScroll)
        APPTransactionPair.default.delegate = self
        if APPTransactionPair.default.isRequestIng == false && APPTransactionPair.default.isRequestFail {
            APPTransactionPair.default.startPair()
        }else {
            let pageCount = self.tabbar?.getPageControllers().count ?? 0
            if pageCount == 0 && APPTransactionPair.default.archiveTitleArray().count != 0 {
                self.updateTabPageView()
            }
        }
        
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.tabbar?.getCurPageController()?.viewWillDisappear()
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        if self.contentScroll == scrollView {
            let contentY = self.contentScroll.contentOffset.y
            if contentY >= cycleView.bottom - kNavi_HEIGHT {
                self.contentScroll.contentOffset.y = cycleView.bottom - kNavi_HEIGHT
                if canScroll {
                    canScroll = false
                    resetCanScroll(canScroll: true)
                }
            }else {
                if self.canScroll == false {
                    self.contentScroll.contentOffset.y = cycleView.bottom - kNavi_HEIGHT
                }
            }
            self.setNavi(percent: contentY / (cycleView.bottom - kNavi_HEIGHT))
        }
    }

    func setNavi(percent: CGFloat) {
        var p = percent
        if percent >= 0.8 {
            p = 1
        }
        navigationBar.alpha = p
        
        if p > 0.5 {
            UIApplication.shared.statusBarStyle = .default
        }else {
            UIApplication.shared.statusBarStyle = .lightContent
        }
        
    }
    
    func resetCanScroll(canScroll: Bool) {
        if let pages = self.tabbar?.getPageControllers() {
            for page in pages {
                if let vc = page as? MarketTabViewController {
                    vc.canScroll = canScroll
                    if canScroll == false {
                        vc.tableView.contentOffset = CGPoint.zero
                    }
                }
            }
        }
    }
    
    func pushScreenLock()  {
        AppSecurityInfo.default.readDic()
        if AppSecurityInfo.default.passWordDic[AppSecurityInfo.SecurityInfo.openScreenKey] == "1" {
            if CYMBShow.currentController() == nil {
                return
            }
            let controller:UIViewController =  CYMBShow.currentController()!
            let pop = ScreenLockerViewController()
            pop.style = .ScreenVerty
            controller.present(pop, animated: false, completion:  nil)
        }
    }
}

extension MarketViewController: SDCycleScrollViewDelegate, AlertDelegate {
    
    func cycleScrollView(_ cycleScrollView: SDCycleScrollView!, didSelectItemAt index: Int) {

    }
    
    func reloadBanner() {
        let urls = self.viewModel.banners.map { (banner) -> String in
            return banner.picPath ?? ""
        }
        self.cycleView.imageURLStringsGroup = urls
    }
}

extension MarketViewController: TransactionPairDelegate {
    
    func requestSuccess(_ data: [String : Any]?) {
        self.updateTabPageView()
    }
    func updateTabPageView() {
        self.tabbar?.removeFromSuperview()
        let titles = APPTransactionPair.default.archiveTitleArray()
        let pages = Array.init(repeating: "MarketTabViewController", count: titles.count)
        self.tabbar = TabbarView(titles: titles, pages: pages, pageData: nil, headerType: .underLine3)
        tabbar?.frame = CGRect(x: 0, y: cycleView.bottom, width: kSCREEN_WIDTH, height: self.view.height - self.tabBarController!.tabBar.height - kNavi_HEIGHT)
        tabbar?.autoresizingMask = .flexibleHeight
        contentScroll.addSubview(tabbar!)
        contentScroll.contentSize = CGSize(width: self.view.width, height: tabbar!.bottom + kNavi_HEIGHT)
        self.tabbar?.getCurPageController()?.viewWillAppear()
    }
    
    func requestFail() {
 
    }
}
